<template>

  <!--头: 引入 CommonHead 子组件-->
  <header class="login-by-account-head">
    <CommonHead title="用户登录"/>
  </header>

  <!--体: 登录表单-->
  <section class="login-by-account-body">

    <van-divider dashed>使用账号密码登录</van-divider>

    <!--表单: 提交表单时触发-->
    <van-form @submit="loginByAccount">

      <!--单元格: 卡片风格-->
      <van-cell-group inset>
        <!--单元格项: 双绑对应的表单数据，双绑对应的表单校验规则，背景提示字，右侧图标，可清除，不提示-->
        <van-field v-model="formData['username']" :rules="formRule['username']"
                   placeholder="请输入登录账号" right-icon="user-o" clearable autocomplete="off"/>
        <van-field v-model="formData['password']" :rules="formRule['password']" type="password"
                   placeholder="请输入登录密码" right-icon="shield-o" clearable autocomplete="off"/>
      </van-cell-group>

      <!--操作区: 登录按钮-->
      <article class="operation">

        <!--提交按钮: 圆角，区块，主要蓝，提交功能-->
        <van-button round block type="primary" native-type="submit">登录</van-button><br/>

        <!--间距-->
        <van-space size="30px">
          <span @click="router.push('/Register')">注册新账号</span>
          <span @click="router.push('/LoginByPhone')">手机号码登录</span>
        </van-space>
      </article>

    </van-form>

  </section>

</template>

<script setup>

import CommonHead from "@/components/CommonHead";
import {LOGIN_BY_ACCOUNT} from '@/api/user';
import {reactive, shallowReactive} from "vue";
import {useStore} from 'vuex';
import router from "@/router";
import {showFailToast, showSuccessToast} from "vant";
import {SUCCESS} from "@/constant";

/* ==================== data ==================== */

// data: Vuex实例，直接使用useStore()会报错
let vuex = useStore();
// data: 登录表单数据对象
let formData = shallowReactive({username: '', password: ''});
// data: 登录表单校验规则
let formRule = reactive({
  username: [
    {required: true, message: '账号不能为空'},
    {pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '账号长度在4-16个字符'}
  ],
  password: [
    {required: true, message: '密码不能为空'},
    {pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '密码长度在4-16个字符'}
  ]
});

/* ==================== method ==================== */

// method: 按账号密码登录
function loginByAccount(){
  // 同步调用登录接口
  LOGIN_BY_ACCOUNT(formData).then(result => {
    let resp = result['data'];
    if (resp.code === SUCCESS) {
      let data = resp.data;
      // 将用户的Token令牌存入sessionStorage中
      sessionStorage.setItem('token', data['token']);
      // 将用户ID存入sessionStorage中
      sessionStorage.setItem('userId', data['user']['userId']);
      // 将用户登录状态存入Vuex中
      vuex.dispatch('setLoginFlag', true);
      // 提示登录成功
      showSuccessToast("登录成功");
      // 跳转到Personal组件
      router.push("/Personal");
    } else {
      showFailToast(resp.message + ': ' + resp.data);
    }
  }).catch(err => console.error(err));
}

</script>

<style scoped lang="scss">

.login-by-account-body {

  /*操作区*/
  .operation {
    margin: 15px; // 外边距
  }

}

</style>